<template>
  <div class="attack-path-view">
    <el-card class="header-card">
      <div class="header-content">
        <h1>攻击路径分析</h1>
        <p class="subtitle">安全漏洞关联分析与攻击链路评估</p>
      </div>
    </el-card>

    <!-- 统计信息面板 - 增强版 -->
    <el-card class="stats-panel slide-in-right">
      <div class="panel-body">
        <div class="stats-header">
          <h3>攻击路径统计</h3>
          <el-tooltip content="基于AI风险评估模型计算的安全指标">
            <el-icon class="info-icon"><InfoFilled /></el-icon>
          </el-tooltip>
          <div class="shine-effect"></div>
        </div>
        <div class="stats-grid">
        <div class="stat-item">
          <div class="stat-icon primary-gradient">
            <el-icon><Link /></el-icon>
            <div class="pulse-effect"></div>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ attackPathStats.totalNodes }}</div>
            <div class="stat-label">总节点数</div>
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-icon danger-gradient">
            <el-icon><WarningFilled /></el-icon>
            <div class="pulse-effect"></div>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ attackPathStats.vulnerabilityCount }}</div>
            <div class="stat-label">漏洞数量</div>
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-icon success-gradient">
            <el-icon><Monitor /></el-icon>
            <div class="pulse-effect"></div>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ attackPathStats.assetCount }}</div>
            <div class="stat-label">资产数量</div>
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-icon warning-gradient">
            <el-icon><Flag /></el-icon>
            <div class="pulse-effect"></div>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ attackPathStats.criticalPaths }}</div>
            <div class="stat-label">关键路径</div>
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-icon" :class="getSeverityGradientClass(attackPathStats.highestRiskScore)">
            <el-icon><Scale /></el-icon>
            <div class="pulse-effect"></div>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ attackPathStats.highestRiskScore }}</div>
            <div class="stat-label">最高风险评分</div>
          </div>
        </div>
        <div class="stat-item">
          <div class="stat-icon" :class="getSeverityGradientClass(attackPathStats.averageRiskScore)">
            <el-icon><DataAnalysis /></el-icon>
            <div class="pulse-effect"></div>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ attackPathStats.averageRiskScore.toFixed(2) }}</div>
            <div class="stat-label">平均风险评分</div>
          </div>
      </div>
    </div>
  </div>
</el-card>

<div class="main-content">
  <!-- 控制区域 -->
  <div class="control-panel fade-in">
    <el-card shadow="hover">
      <div class="panel-body">
        <div class="panel-section">
          <h3>布局控制</h3>
          <el-radio-group v-model="currentLayout" size="small" @change="applyLayout">
            <el-radio-button label="grid">网格布局</el-radio-button>
            <el-radio-button label="circle">环形布局</el-radio-button>
            <el-radio-button label="cose">力导向布局</el-radio-button>
            <el-radio-button label="hierarchy">层次布局</el-radio-button>
          </el-radio-group>
        </div>

        <div class="panel-section">
          <h3>视图控制</h3>
          <el-button-group size="small">
            <el-button @click="zoomIn" title="放大">
              <el-icon><ZoomIn /></el-icon>
            </el-button>
            <el-button @click="zoomOut" title="缩小">
              <el-icon><ZoomOut /></el-icon>
            </el-button>
            <el-button @click="zoomToFit" title="适应屏幕">
              <el-icon><FullScreen /></el-icon>
            </el-button>
            <el-button @click="resetHighlighting" title="重置高亮">
              <el-icon><Refresh /></el-icon>
            </el-button>
          </el-button-group>
        </div>

        <div class="panel-section">
          <h3>动画控制</h3>
          <el-button size="small" @click="animateAttackPath" type="primary">
            <el-icon><VideoPlay /></el-icon> 播放攻击路径动画
          </el-button>
        </div>
      </div>

          <div class="panel-section">
            <h3>风险筛选</h3>
            <el-select v-model="riskFilter" placeholder="筛选风险等级" size="small" @change="filterByRisk">
              <el-option label="全部风险" value="all"></el-option>
              <el-option label="高危风险" value="high"></el-option>
              <el-option label="中危风险" value="medium"></el-option>
              <el-option label="低危风险" value="low"></el-option>
            </el-select>
          </div>
        </el-card>
      </div>

      <!-- 可视化区域 -->
      <div class="visualization-panel slide-in-left" style="animation-delay: 0.3s">
        <el-card class="visualization-card">
          <div id="cy-container" class="cy-container"></div>
        </el-card>
      </div>

      <!-- 节点详情面板 -->
      <div class="detail-panel fade-in" v-if="selectedNode" style="animation-delay: 0.2s">
        <el-card shadow="hover">
          <div class="panel-header">
            <h3>节点详情</h3>
            <el-button size="small" @click="closeNodeDetails" type="text">
              <el-icon><Close /></el-icon>
            </el-button>
          </div>
          <div class="panel-body">
            <div class="node-details" v-if="selectedNode">
                <div class="detail-item hover-lift">
                  <span class="detail-label">节点类型:</span>
                  <span class="detail-value">{{ getNodeTypeLabel(selectedNode.data('type')) }}</span>
                </div>
            </div>
            <div class="detail-item hover-lift">
              <span class="detail-label">节点ID:</span>
              <span class="detail-value">{{ selectedNode.id() }}</span>
            </div>
            <div class="detail-item hover-lift">
              <span class="detail-label">名称:</span>
              <span class="detail-value">{{ selectedNode.data('name') }}</span>
            </div>
            <div class="detail-item hover-lift" v-if="selectedNode.data('risk_score')">
              <span class="detail-label">风险评分:</span>
              <span class="detail-value" :class="getRiskScoreClass(selectedNode.data('risk_score')) + ' pulse-soft'" style="animation-duration: 3s">
                {{ selectedNode.data('risk_score') }}
              </span>
            </div>
            <div class="detail-item hover-lift" v-if="selectedNode.data('severity')">
              <span class="detail-label">严重程度:</span>
              <el-tag :type="getSeverityType(selectedNode.data('severity'))" class="pulse-soft" style="animation-duration: 3s">
                {{ getSeverityLabel(selectedNode.data('severity')) }}
              </el-tag>
            </div>
            <div class="detail-item" v-if="selectedNode.data('description')">
              <span class="detail-label">描述:</span>
              <p class="detail-description">{{ selectedNode.data('description') }}</p>
            </div>
            <div class="detail-item" v-if="selectedNode.data('remediation')">
              <span class="detail-label">修复建议:</span>
              <p class="detail-description">{{ selectedNode.data('remediation') }}</p>
              <el-button size="small" type="success" @click="copyRemediation">
                <el-icon><CopyDocument /></el-icon> 复制修复建议
              </el-button>
            </div>
            <div class="detail-item" v-if="selectedNode.data('confidence') !== undefined">
              <span class="detail-label">AI置信度:</span>
              <div class="confidence-meter">
                <div class="confidence-bar" :style="{ width: selectedNode.data('confidence') + '%' }"></div>
                <span class="confidence-text">{{ selectedNode.data('confidence') }}%</span>
              </div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import Cytoscape from 'cytoscape';
import { InfoFilled, ZoomIn, ZoomOut, FullScreen, Refresh, VideoPlay, Close } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import apiService from '@/services/apiService'; // 导入API服务

// 状态管理
const cy = ref(null);
const selectedNode = ref(null);
const currentLayout = ref('cose');
const riskFilter = ref('all');
const attackPathStats = ref({
  totalNodes: 0,
  vulnerabilityCount: 0,
  assetCount: 0,
  criticalPaths: 0,
  highestRiskScore: 0,
  averageRiskScore: 0
});

// 获取风险等级对应的颜色
function getSeverityColor(score) {
  if (score >= 80) return '#f56c6c';
  if (score >= 60) return '#e6a23c';
  if (score >= 40) return '#67c23a';
  return '#909399';
}

// 获取风险等级对应的渐变样式类名
function getSeverityGradientClass(score) {
  if (score >= 80) return 'danger-gradient';
  if (score >= 60) return 'warning-gradient';
  if (score >= 40) return 'success-gradient';
  return 'primary-gradient';
}

// 获取节点类型标签
function getNodeTypeLabel(type) {
  const typeMap = {
    vulnerability: '漏洞',
    asset: '资产',
    user: '用户',
    network: '网络'
  };
  return typeMap[type] || '未知';
}

// 获取风险评分样式类名
function getRiskScoreClass(score) {
  if (score >= 80) return 'risk-high';
  if (score >= 60) return 'risk-medium';
  if (score >= 40) return 'risk-low';
  return 'risk-info';
}

// 其他状态变量
const isLoading = ref(false);
const selectedTaskId = ref('');
const taskList = ref([]);

// 初始化
onMounted(() => {
  // 从会话存储获取上次的任务ID
  const savedTaskId = sessionStorage.getItem('currentTaskId');
  if (savedTaskId) {
    selectedTaskId.value = savedTaskId;
  }
  
  // 加载任务列表和攻击路径数据
  loadTaskList();
  loadAttackPathData();
});

// 加载任务列表
const loadTaskList = async () => {
  try {
    isLoading.value = true;
    
    // 先尝试获取真实的任务列表
    try {
      console.log('正在尝试获取真实任务列表...');
      const response = await apiService.getTaskList();
      if (response?.tasks && response.tasks.length > 0) {
        taskList.value = response.tasks;
        console.log('成功获取真实任务列表');
        ElMessage.success('任务列表加载成功');
        return;
      }
    } catch (apiError) {
      console.log('任务列表API调用失败，将使用模拟数据:', apiError.message);
    }
    
    // API调用失败或无数据时，使用模拟数据
    console.log('使用模拟任务列表数据');
    taskList.value = [
      {
        task_id: 'SCAN-2025-1017-001',
        target: 'http://example.com',
        created_at: new Date().toISOString(),
        status: 'completed'
      },
      {
        task_id: 'SCAN-2025-1016-001',
        target: 'https://test-application.org',
        created_at: new Date(Date.now() - 86400000).toISOString(),
        status: 'completed'
      }
    ];
    
    ElMessage.success('任务列表加载成功（使用模拟数据）');
  } catch (error) {
    console.error('加载任务列表失败:', error);
    ElMessage.error('任务列表加载失败');
  } finally {
    isLoading.value = false;
  }
};

// 加载攻击路径数据（优先真实数据，失败后使用模拟数据）
const loadAttackPathData = async () => {
  try {
    isLoading.value = true;
    
    // 先尝试获取真实的攻击路径数据
    try {
      console.log('正在尝试获取真实攻击路径数据...');
      
      // 如果有选中的任务ID，尝试获取该任务的攻击路径
      const taskId = selectedTaskId.value || (taskList.value.length > 0 ? taskList.value[0].task_id : null);
      
      if (taskId) {
        // 尝试获取真实的攻击路径数据
        const response = await apiService.getAttackPath(taskId);
        if (response?.graph && response.graph.nodes && response.graph.nodes.length > 0) {
          console.log('成功获取真实攻击路径数据');
          
          // 初始化Cytoscape实例
          initCytoscape(response.graph);
          
          // 计算统计信息
          calculateStatistics(response.graph);
          
          ElMessage.success('攻击路径加载成功');
          return;
        }
      }
    } catch (apiError) {
      console.log('攻击路径API调用失败，将使用模拟数据:', apiError.message);
    }
    
    // API调用失败或无数据时，使用模拟数据
    console.log('使用模拟攻击路径数据');
    const mockData = generateMockAttackPathData();
    
    // 初始化Cytoscape实例
    initCytoscape(mockData);
    
    // 计算统计信息
    calculateStatistics(mockData);
    
    ElMessage.success('攻击路径加载成功（使用模拟数据）');
  } catch (error) {
    console.error('加载攻击路径失败:', error);
    ElMessage.error('攻击路径加载失败');
  } finally {
    isLoading.value = false;
  }
};

// 生成模拟攻击路径数据
const generateMockAttackPathData = () => {
  const nodes = [
    { data: { id: 'asset-1', type: 'asset', name: 'Web服务器', risk_score: 0 } },
    { data: { id: 'asset-2', type: 'asset', name: '数据库服务器', risk_score: 0 } },
    { data: { id: 'asset-3', type: 'asset', name: '内部网络', risk_score: 0 } },
    { data: { id: 'vuln-1', type: 'vulnerability', name: 'SQL注入', risk_score: 90, severity: 'high', 
              description: 'SQL注入漏洞允许攻击者在数据库查询中插入恶意代码，可能导致数据泄露或数据库被接管。',
              remediation: '1. 使用参数化查询\n2. 实施输入验证\n3. 应用最小权限原则\n4. 使用ORM框架',
              confidence: 95 } },
    { data: { id: 'vuln-2', type: 'vulnerability', name: 'XSS跨站脚本', risk_score: 65, severity: 'medium',
              description: '跨站脚本漏洞允许攻击者向网页注入恶意脚本，当其他用户浏览时执行。',
              remediation: '1. 实施内容安全策略\n2. 对用户输入进行验证和转义\n3. 使用框架的自动转义功能',
              confidence: 88 } },
    { data: { id: 'vuln-3', type: 'vulnerability', name: '未授权访问', risk_score: 85, severity: 'high',
              description: '未授权访问漏洞允许攻击者绕过身份验证，访问受限资源或执行特权操作。',
              remediation: '1. 实施严格的访问控制\n2. 对所有API端点进行认证检查\n3. 实施基于角色的访问控制',
              confidence: 92 } },
    { data: { id: 'vuln-4', type: 'vulnerability', name: '弱密码', risk_score: 55, severity: 'medium',
              description: '弱密码策略增加账户被暴力破解的风险，可能导致未授权访问。',
              remediation: '1. 实施强密码策略\n2. 支持多因素认证\n3. 实施账户锁定机制',
              confidence: 82 } }
  ];
  
  const edges = [
    { data: { id: 'e1', source: 'asset-1', target: 'vuln-1', label: '存在' } },
    { data: { id: 'e2', source: 'asset-1', target: 'vuln-2', label: '存在' } },
    { data: { id: 'e3', source: 'vuln-1', target: 'vuln-3', label: '可利用' } },
    { data: { id: 'e4', source: 'vuln-3', target: 'asset-2', label: '访问' } },
    { data: { id: 'e5', source: 'asset-2', target: 'vuln-4', label: '存在' } },
    { data: { id: 'e6', source: 'vuln-4', target: 'asset-3', label: '渗透' } }
  ];
  
  return { nodes, edges };
};

// 初始化Cytoscape
const initCytoscape = (graphData) => {
  // 销毁现有实例
  if (cy.value) {
    cy.value.destroy();
  }
  
  // 获取容器元素
  const container = document.getElementById('cy-container');
  if (!container) return;
  
  // 创建新实例
  cy.value = Cytoscape({
    container: container,
    elements: graphData,
    style: [
      // 基础节点样式
      {
        selector: 'node',
        style: {
          'label': 'data(name)',
          'font-size': '12px',
          'font-weight': '500',
          'text-valign': 'center',
          'text-halign': 'center',
          'height': 60,
          'width': 60,
          'border-width': 2,
          'transition-property': 'background-color, border-color, width, height, opacity',
          'transition-duration': '0.3s',
          'shadow-color': '#ccc',
          'shadow-opacity': 0.5,
          'shadow-offset-x': 0,
          'shadow-offset-y': 2,
          'shadow-blur': 5
        }
      },
      
      // 资产节点样式
      {
        selector: 'node[type="asset"]',
        style: {
          'shape': 'rectangle',
          'background-color': '#409eff',
          'color': '#fff',
          'border-color': '#66b1ff',
          'font-weight': 'bold',
          'padding': '10px',
          'shadow-color': '#409eff',
          'shadow-opacity': 0.4,
          'shadow-blur': 8
        }
      },
      
      // 漏洞节点样式 - 高风险
      {
        selector: 'node[type="vulnerability"][severity="high"]',
        style: {
          'shape': 'ellipse',
          'background-color': '#f56c6c',
          'color': '#fff',
          'border-color': '#f78989',
          'border-width': 3,
          'shadow-color': '#f56c6c',
          'shadow-opacity': 0.6,
          'shadow-blur': 12,
          'text-shadow': '0 1px 2px rgba(0,0,0,0.3)',
          'width': 65,
          'height': 65
        }
      },
      
      // 漏洞节点样式 - 中风险
      {
        selector: 'node[type="vulnerability"][severity="medium"]',
        style: {
          'shape': 'ellipse',
          'background-color': '#e6a23c',
          'color': '#fff',
          'border-color': '#ebb563',
          'shadow-color': '#e6a23c',
          'shadow-opacity': 0.4,
          'shadow-blur': 8
        }
      },
      
      // 漏洞节点样式 - 低风险
      {
        selector: 'node[type="vulnerability"][severity="low"]',
        style: {
          'shape': 'ellipse',
          'background-color': '#909399',
          'color': '#fff',
          'border-color': '#a6a9ad',
          'shadow-color': '#909399',
          'shadow-opacity': 0.3,
          'shadow-blur': 5,
          'width': 55,
          'height': 55
        }
      },
      
      // 边样式
      {
        selector: 'edge',
        style: {
          'width': 2.5,
          'line-color': '#909399',
          'target-arrow-color': '#909399',
          'target-arrow-shape': 'triangle',
          'curve-style': 'bezier',
          'label': 'data(label)',
          'label-font-size': '10px',
          'transition-property': 'line-color, width, opacity',
          'transition-duration': '0.3s',
          'line-style': 'solid'
        }
      },
      
      // 鼠标悬停样式增强
      {
        selector: 'node:hover',
        style: {
          'z-index': 1000,
          'transform': 'scale(1.05)',
          'shadow-blur': 8
        }
      },
      
      // 攻击路径边样式
      {
        selector: '.attack-path-edge',
        style: {
          'width': 3,
          'line-color': '#409eff',
          'target-arrow-color': '#409eff',
          'opacity': 0.8,
          'line-style': 'dashed'
        }
      },
      
      // 选中节点样式
      {
        selector: 'node:selected',
        style: {
          'border-color': '#ff4d4f',
          'border-width': 4,
          'z-index': 9999,
          'height': 70,
          'width': 70,
          'shadow-color': '#ff4d4f',
          'shadow-opacity': 0.5,
          'shadow-blur': 10
        }
      },
      

      
      // 高亮路径节点样式
      {
        selector: '.highlighted',
        style: {
          'background-color': '#722ed1',
          'border-color': '#9254de',
          'border-width': 3,
          'opacity': 1,
          'shadow-color': '#722ed1',
          'shadow-opacity': 0.6,
          'shadow-blur': 12
        }
      },
      
      // 高亮路径边样式
      {
        selector: '.path-highlight',
        style: {
          'line-color': '#722ed1',
          'target-arrow-color': '#722ed1',
          'width': 4,
          'opacity': 1
        }
      },
      
      // 非高亮元素（降低透明度）
      {
        selector: '.faded',
        style: {
          'opacity': 0.3
        }
      }
    ],
    layout: {
      name: 'cose',
      idealEdgeLength: 150,
      nodeOverlap: 30,
      padding: 60,
      randomize: true,
      componentSpacing: 150,
      animate: true,
      animationDuration: 1000
    },
    wheelSensitivity: 0.1,
    minZoom: 0.5,
    maxZoom: 3.0
  });
  
  // 添加事件监听
  addEventListeners();
};

// 添加事件监听器
const addEventListeners = () => {
  if (!cy.value) return;
  
  // 节点点击事件
  cy.value.on('tap', 'node', (evt) => {
    const node = evt.target;
    selectedNode.value = node;
    highlightAttackPath(node);
  });
  
  // 空白处点击事件
  cy.value.on('tap', (evt) => {
    if (evt.target === cy.value) {
      selectedNode.value = null;
      resetHighlighting();
    }
  });
  
  // 键盘事件
  cy.value.on('keydown', (evt) => {
    if (evt.originalEvent.keyCode === 27) { // ESC键
      selectedNode.value = null;
      resetHighlighting();
    }
  });
};

// 计算统计信息
const calculateStatistics = (graphData) => {
  const nodes = graphData.nodes || [];
  const edges = graphData.edges || [];
  
  const vulnerabilities = nodes.filter(n => n.data.type === 'vulnerability');
  const assets = nodes.filter(n => n.data.type === 'asset');
  const riskScores = vulnerabilities.map(n => n.data.risk_score || 0);
  
  attackPathStats.value = {
    totalNodes: nodes.length,
    vulnerabilityCount: vulnerabilities.length,
    assetCount: assets.length,
    criticalPaths: edges.length,
    highestRiskScore: riskScores.length > 0 ? Math.max(...riskScores) : 0,
    averageRiskScore: riskScores.length > 0 ? riskScores.reduce((a, b) => a + b, 0) / riskScores.length : 0
  };
};

// 高亮攻击路径
const highlightAttackPath = (node) => {
  if (!cy.value) return;
  
  // 重置之前的高亮
  resetHighlighting();
  
  // 获取所有相关节点和边
  const connectedNodes = node.successors().add(node.predecessors()).add(node);
  const connectedEdges = node.connectedEdges();
  
  // 对非路径元素添加淡化效果
  cy.value.elements().not(connectedNodes.union(connectedEdges)).addClass('faded');
  
  // 高亮路径节点和边
  connectedNodes.addClass('highlighted');
  connectedEdges.addClass('path-highlight');
};

// 重置高亮
const resetHighlighting = () => {
  if (!cy.value) return;
  cy.value.elements().removeClass('highlighted path-highlight faded');
};

// 应用布局
const applyLayout = (layoutName) => {
  if (!cy.value) return;
  
  resetHighlighting();
  
  const layouts = {
    grid: {
      name: 'grid',
      rows: 'auto',
      animate: true,
      animationDuration: 800,
      fit: true
    },
    circle: {
      name: 'circle',
      radius: 200,
      animate: true,
      animationDuration: 800,
      fit: true
    },
    cose: {
      name: 'cose',
      idealEdgeLength: 150,
      nodeOverlap: 30,
      padding: 60,
      animate: true,
      animationDuration: 1000,
      fit: true
    },
    hierarchy: {
      name: 'breadthfirst',
      directed: true,
      padding: 30,
      animate: true,
      animationDuration: 1000,
      fit: true
    }
  };
  
  if (layouts[layoutName]) {
    cy.value.layout(layouts[layoutName]).run();
    ElMessage.success(`已应用${getLayoutName(layoutName)}布局`);
  }
};

// 获取布局名称
const getLayoutName = (layoutName) => {
  const names = {
    grid: '网格',
    circle: '环形',
    cose: '力导向',
    hierarchy: '层次'
  };
  return names[layoutName] || layoutName;
};

// 缩放控制函数
const zoomIn = () => {
  if (!cy.value) return;
  cy.value.zoom(cy.value.zoom() * 1.2);
};

const zoomOut = () => {
  if (!cy.value) return;
  cy.value.zoom(cy.value.zoom() * 0.8);
};

const zoomToFit = () => {
  if (!cy.value) return;
  resetHighlighting();
  cy.value.fit(null, 60);
};

// 动画播放攻击路径
const animateAttackPath = () => {
  if (!cy.value) return;
  
  const vulnNodes = cy.value.nodes('[type="vulnerability"]');
  let currentIndex = 0;
  
  const animationInterval = setInterval(() => {
    if (currentIndex >= vulnNodes.length) {
      clearInterval(animationInterval);
      resetHighlighting();
      return;
    }
    
    const node = vulnNodes[currentIndex];
    selectedNode.value = node;
    highlightAttackPath(node);
    currentIndex++;
  }, 2000);
  
  return animationInterval;
};

// 风险筛选
const filterByRisk = (riskLevel) => {
  if (!cy.value) return;
  
  resetHighlighting();
  
  switch (riskLevel) {
    case 'high':
      cy.value.nodes().not('[severity="high"]').addClass('faded');
      break;
    case 'medium':
      cy.value.nodes().not('[severity="medium"]').addClass('faded');
      break;
    case 'low':
      cy.value.nodes().not('[severity="low"]').addClass('faded');
      break;
    default:
      cy.value.nodes().removeClass('faded');
  }
};

// 关闭节点详情
const closeNodeDetails = () => {
  selectedNode.value = null;
  resetHighlighting();
};

// 复制修复建议
const copyRemediation = async () => {
  if (!selectedNode.value || !selectedNode.value.data('remediation')) {
    ElMessage.warning('没有可复制的修复建议');
    return;
  }
  
  try {
    await navigator.clipboard.writeText(selectedNode.value.data('remediation'));
    ElMessage.success('修复建议已复制到剪贴板');
  } catch (error) {
    console.error('复制失败:', error);
    ElMessage.error('复制失败，请手动复制');
  }
};

// 获取严重程度标签
const getSeverityLabel = (severity) => {
  const labels = {
    'high': '高',
    'medium': '中',
    'low': '低'
  };
  return labels[severity] || severity;
};

// 获取严重程度对应的标签类型
const getSeverityType = (severity) => {
  const types = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'success'
  };
  return types[severity] || 'info';
};
</script>

<style scoped>
.attack-path-view {
  padding: 20px;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header-card {
  margin-bottom: 24px;
  border-radius: 8px;
  background: linear-gradient(135deg, #409eff 0%, #67c23a 100%);
  color: white;
  border: none;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.header-content {
  padding: 20px;
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 28px;
  font-weight: 600;
}

.subtitle {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.stats-panel {
  margin-bottom: 24px;
  border-radius: 8px;
  overflow: hidden;
}

.stats-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 16px 0;
  position: relative;
}

.stats-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 700;
  color: #303133;
  background: linear-gradient(90deg, #303133 0%, #606266 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
}

/* 增强卡片样式 */
.stats-panel {
  position: relative;
  border-radius: 16px;
  overflow: hidden;
}

.stats-panel::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 4px;
  background: linear-gradient(90deg, #409eff, #67c23a, #e6a23c, #f56c6c);
}

/* 增强节点详情面板样式 */
.detail-panel .el-card {
  border-radius: 16px;
  border: 1px solid rgba(224, 231, 255, 0.8);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.detail-panel .el-card:hover {
  box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

/* 增强按钮样式 */
.el-button {
  border-radius: 8px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-button::after {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 5px;
  height: 5px;
  background: rgba(255, 255, 255, 0.5);
  opacity: 0;
  border-radius: 100%;
  transform: scale(1, 1) translate(-50%, -50%);
  transform-origin: 50% 50%;
}

.el-button:focus::after {
  animation: ripple 0.6s ease-out;
}

@keyframes ripple {
  0% {
    transform: scale(0, 0);
    opacity: 0.5;
  }
  100% {
    transform: scale(20, 20);
    opacity: 0;
  }
}

/* 增强控制面板样式 */
.control-panel .el-card {
  border-radius: 16px;
  border: 1px solid rgba(224, 231, 255, 0.8);
  background: linear-gradient(180deg, #ffffff 0%, #f8f9fa 100%);
}

/* 增强单选按钮组样式 */
.el-radio-group .el-radio-button__inner {
  border-radius: 6px;
  transition: all 0.3s ease;
}

.el-radio-group .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 增强选择器样式 */
.el-select {
  width: 100%;
}

.el-input__wrapper {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.el-input__wrapper:hover {
  border-color: #66b1ff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.1);
}

/* 增强标签样式 */
.el-tag {
  border-radius: 6px;
  padding: 4px 12px;
  font-size: 12px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.el-tag:hover {
  transform: scale(1.05);
}

/* 增强Cytoscape容器样式 */
.cy-container {
  border-radius: 16px;
  background: linear-gradient(135deg, #ffffff 0%, #f5f7fa 100%);
  border: 1px solid rgba(224, 231, 255, 0.8);
  box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.stat-item {
  display: flex;
  align-items: center;
  background: #f8f9fa;
  padding: 16px;
  border-radius: 12px;
  transition: all 0.3s ease;
  border: 1px solid transparent;
  position: relative;
  overflow: hidden;
}

.stat-item:hover {
  transform: translateY(-2px) scale(1.02);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  border-color: rgba(64, 158, 255, 0.2);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 16px;
  font-size: 20px;
  position: relative;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 渐变背景样式 */
.primary-gradient {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.danger-gradient {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
}

.success-gradient {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.warning-gradient {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
}

/* 脉冲效果 */
.pulse-effect {
  position: absolute;
  width: 100%;
  height: 100%;
  background: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  transform: scale(0);
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    transform: scale(0);
    opacity: 1;
  }
  100% {
    transform: scale(1.5);
    opacity: 0;
  }
}

/* 闪光效果 */
.shine-effect {
  position: absolute;
  top: 0;
  left: -100%;
  width: 50%;
  height: 100%;
  background: linear-gradient(
    to right,
    rgba(255, 255, 255, 0) 0%,
    rgba(255, 255, 255, 0.3) 50%,
    rgba(255, 255, 255, 0) 100%
  );
  transform: skewX(-20deg);
  animation: shine 3s infinite;
}

@keyframes shine {
  0% {
    left: -100%;
  }
  20%, 100% {
    left: 150%;
  }
}

.info-icon {
  cursor: pointer;
  color: #409eff;
  transition: transform 0.3s ease;
}

.info-icon:hover {
  transform: rotate(360deg);
}

.stat-content .stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  line-height: 1.2;
}

.stat-content .stat-label {
  font-size: 12px;
  color: #606266;
  margin-top: 2px;
}

.main-content {
  display: grid;
  grid-template-columns: 280px 1fr 320px;
  gap: 24px;
  align-items: start;
}

.control-panel, .detail-panel {
  position: sticky;
  top: 20px;
  background-color: #ffffff;
  border-radius: 16px;
  border: 1px solid rgba(224, 231, 255, 0.8);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  transition: all 0.3s ease;
}

.control-panel:hover, .detail-panel:hover {
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.visualization-panel {
  min-height: 600px;
  background-color: #ffffff;
  border-radius: 16px;
  border: 1px solid rgba(224, 231, 255, 0.8);
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.panel-section {
  margin-bottom: 24px;
  position: relative;
}

.panel-section h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  position: relative;
  display: inline-block;
}

.panel-section h3::after {
  content: '';
  position: absolute;
  left: 0;
  bottom: -4px;
  width: 30px;
  height: 3px;
  background: linear-gradient(90deg, #409eff 0%, #66b1ff 100%);
  border-radius: 3px;
  transition: width 0.3s ease;
}

.panel-section:hover h3::after {
  width: 100%;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #f5f7fa 0%, #ffffff 100%);
  border-bottom: 1px solid rgba(224, 231, 255, 0.8);
}

.panel-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.panel-body {
  padding: 16px;
}

.cy-container {
  width: 100%;
  height: 600px;
  border-radius: 8px;
  background-color: #ffffff;
  border: 1px solid #ebeef5;
}

.node-details .detail-item {
  margin-bottom: 16px;
}

.node-details .detail-label {
  font-size: 12px;
  color: #909399;
  display: block;
  margin-bottom: 4px;
}

.node-details .detail-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
}

.detail-description {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin: 8px 0 12px 0;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
  position: relative;
  overflow: hidden;
  transition: all 0.3s ease;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.detail-description:hover {
  background-color: #f0f2f5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transform: translateX(2px);
}

.node-details .detail-item:last-child .detail-description {
  border-left-color: #67c23a;
}

.risk-high { 
  color: #f56c6c; 
  font-weight: 600;
}
.risk-medium { 
  color: #e6a23c; 
  font-weight: 600;
}
.risk-low { 
  color: #67c23a; 
  font-weight: 600;
}
.risk-info { 
  color: #909399; 
  font-weight: 600;
}

/* 风险评分徽章样式 */
.risk-score-badge {
  display: inline-block;
  padding: 4px 12px;
  border-radius: 16px;
  font-weight: 600;
  color: white;
  font-size: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
}

.risk-score-badge:hover {
  transform: scale(1.1);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.confidence-meter {
  position: relative;
  width: 100%;
  height: 12px;
  background-color: #f0f2f5;
  border-radius: 6px;
  overflow: hidden;
  margin-top: 8px;
  box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
}

.confidence-bar {
  height: 100%;
  background: linear-gradient(90deg, #67c23a 0%, #409eff 100%);
  border-radius: 6px;
  transition: width 1s ease;
  position: relative;
  overflow: hidden;
}

.confidence-bar::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(
    90deg,
    rgba(255, 255, 255, 0) 0%,
    rgba(255, 255, 255, 0.4) 50%,
    rgba(255, 255, 255, 0) 100%
  );
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}

.confidence-text {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  font-size: 12px;
  font-weight: 600;
  color: #303133;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8);
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .main-content {
    grid-template-columns: 250px 1fr 280px;
  }
}

@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 1fr;
    gap: 16px;
  }
  
  .control-panel, .detail-panel {
    position: relative;
    top: 0;
  }
  
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  }
}

@media (max-width: 768px) {
  .attack-path-view {
    padding: 12px;
  }
  
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }
  
  .stat-item {
    padding: 12px;
  }
  
  .cy-container {
    height: 400px;
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(20px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes pulseSoft {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.02);
  }
  100% {
    transform: scale(1);
  }
}

/* 添加到关键元素的动画类 */
.fade-in {
  animation: fadeIn 0.5s ease-out;
}

.slide-in-left {
  animation: slideInLeft 0.5s ease-out;
}

.slide-in-right {
  animation: slideInRight 0.5s ease-out;
}

.pulse-soft {
  animation: pulseSoft 2s infinite;
}

/* 交互增强 */
.hover-lift {
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.hover-lift:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

/* 加载状态 */
.loading-skeleton {
  background: linear-gradient(90deg, #f0f0f0 25%, #f8f8f8 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: loading 1.5s infinite;
}

@keyframes loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

.stat-item, .detail-panel, .control-panel {
  animation: fadeIn 0.3s ease-out;
}

/* 滚动条样式优化 */
.detail-description::-webkit-scrollbar {
  width: 4px;
}

.detail-description::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.detail-description::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 2px;
}

.detail-description::-webkit-scrollbar-thumb:hover {
  background: #909399;
}
</style>